﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.Design;
using System.Text;

namespace Hanhud.Web.UI.WebControls
{
    public class FlashUploadItem
    {
        public string FileID { get; private set; }
        public string Title { get; set; }
        public string FileName { get; set; }
        public bool IsStored { get; set; }

        public FlashUploadItem(string fileID, string fileName, bool stored)
        {
            this.FileID = fileID;
            this.FileName = fileName;
            this.IsStored = stored;
            this.Title = string.Empty;
        }

        public override bool Equals(object obj)
        {
            return ((FlashUploadItem)obj).FileID == this.FileID;
        }
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
        public override string ToString()
        {
            return string.Format("{0}&{1}&{2}", this.FileID, this.FileName, this.IsStored ? "1" : "0");
        }
    }
}

namespace Hanhud.Web.UI.WebControls
{
    [AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(System.Security.Permissions.SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [Designer(typeof(FlashUploadDesigner))]
    [ToolboxData("<{0}:FlashUpload runat=\"server\"></{0}:FlashUpload>")]
    public class FlashUpload : CompositeControl, INamingContainer
    {
        #region Privates
        private ITemplate _layoutTemplate = null;
        private ITemplate _errorTemplate = null;
        //private CTemplateOwner _templateOwner;
        private FlashUploadSetting _customSettings = null;
        //private string _fileUploadedNameCollection = string.Empty;
        private HtmlInputHidden _ctrlFileUploadCollection = null;
        private HtmlInputHidden _ctrlSelectedIndex = null;
        #endregion

        #region Templates
        [Browsable(false)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DefaultValue(typeof(ITemplate), "")]
        [Description("Layout Template")]
        [TemplateContainer(typeof(FlashUpload))]
        public ITemplate LayoutTemplate
        {
            get { return _layoutTemplate; }
            set { _layoutTemplate = value; }
        }
        [Browsable(false)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DefaultValue(typeof(ITemplate), "")]
        [Description("Layout Template")]
        [TemplateContainer(typeof(FlashUpload))]
        public ITemplate ErrorTemplate
        {
            get { return _errorTemplate; }
            set { _errorTemplate = value; }
        }
        #endregion

        #region Properties
        [Bindable(true)]
        [Category("Settings")]
        [Description("Path to the script file. Default = ~/FlashUpload/JS/")]
        [Localizable(true)]
        public string CoreScriptPath { get; set; }
        [Bindable(true)]
        [Category("Settings")]
        [Description("Path to the flash file. Default = ~/FlashUpload/SWF/swfupload.swf")]
        [Localizable(true)]
        public string CoreFlashFile { get; set; }
        [Bindable(true)]
        [Category("Settings")]
        [Description("Path to the page or handler that will upload the file. Default = ~/FlashUpload/Handler/UploadHandler.ashx.")]
        [Localizable(true)]
        public string CoreHandlerFile { get; set; }
        [Bindable(true)]
        [Category("Settings")]
        [Description("Path to the preview handler file. Default = ~/FlashUpload/Handler/PreviewHandler.ashx")]
        [Localizable(true)]
        public string PreviewHandlerFile { get; set; }
        [Bindable(true)]
        [Category("Callback")]
        [Description("JS function's name that is automatic call when upload complete.")]
        [Localizable(true)]
        public string UploadCompleteCallback { get; set; }
        [Bindable(true)]
        [Category("Settings")]
        [Description("Folder location for uploaded files (e.g., ~/FlashUpload/Temp/).")]
        [Localizable(true)]
        public string SaveToPath { get; set; }
        [Bindable(true)]
        [Category("Appearance")]
        [Description("Button display text.")]
        [Localizable(true)]
        public string ButtonText { get; set; }
        [Category("CustomSettings")]
        [Description("The custom settings to be applied to flash control.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [NotifyParentProperty(true)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public FlashUploadSetting CustomSettings
        {
            get
            {
                _customSettings = ViewState["CustomSettings"] != null ? (FlashUploadSetting)ViewState["CustomSettings"] : (new FlashUploadSetting());
                return _customSettings;
            }
            set
            {
                ViewState["CustomSettings"] = _customSettings = value;
            }
        }
        #endregion

        #region Public Fields
        private string _fileProgressID;
        public string FileProgressID
        {
            get
            {
                _fileProgressID = ViewState["FileProgressID"] != null ? ViewState["FileProgressID"].ToString() : DateTime.Now.Ticks.ToString();

                return _fileProgressID;
            }
            set
            {
                ViewState["FileProgressID"] = _fileProgressID = value;
            }
        }
        public IEnumerable<Hanhud.Web.UI.WebControls.FlashUploadItem> FileUploadCollection
        {
            get
            {
                EnsureChildControls();

                List<Hanhud.Web.UI.WebControls.FlashUploadItem> fileUploadCollection = new List<Hanhud.Web.UI.WebControls.FlashUploadItem>();
                string[] fileUploadObjectCollection = _ctrlFileUploadCollection.Value.Split(new string[] { "$$" }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < fileUploadObjectCollection.Length; i++)
                {
                    string[] fileUploadObject = fileUploadObjectCollection[i].Split('&');
                    if (fileUploadObject.Length == 3)
                        fileUploadCollection.Add(new Hanhud.Web.UI.WebControls.FlashUploadItem(fileUploadObject[0], fileUploadObject[1], fileUploadObject[2] == "1" ? true : false));
                }
                return fileUploadCollection;
            }
        }
        public int SelectedIndex
        {
            get
            {
                EnsureChildControls();
                int selectedIndex = -1;
                if (!string.IsNullOrEmpty(_ctrlSelectedIndex.Value) && int.TryParse(_ctrlSelectedIndex.Value, out selectedIndex)) { }
                return selectedIndex;
            }
            set
            {
                EnsureChildControls();
                _ctrlSelectedIndex.Value = value.ToString();
            }
        }
        #endregion

        public void AddFile(string fileID, string fileName)
        {
            AddFile(fileID, fileName, false);
        }
        public void AddFile(string fileID, string fileName, bool stored)
        {
            if (!string.IsNullOrEmpty(fileName))
            {
                EnsureChildControls();

                if (!string.IsNullOrEmpty(_ctrlFileUploadCollection.Value))
                    _ctrlFileUploadCollection.Value += string.Format("$${0}&{1}&{2}", fileID, fileName, stored ? "1" : "0");
                else
                    _ctrlFileUploadCollection.Value = string.Format("{0}&{1}&{2}", fileID, fileName, stored ? "1" : "0");
            }
        }

        #region Constructor
        public FlashUpload()
            : base()
        {
            this.CoreScriptPath = "~/FlashUpload/JS/";
            this.CoreFlashFile = "~/FlashUpload/SWF/swfupload.swf";
            this.CoreHandlerFile = "~/FlashUpload/Handler/UploadHandler.ashx";
            this.PreviewHandlerFile = "~/FlashUpload/Handler/PreviewHandler.ashx";
            this.SaveToPath = "~/FlashUpload/Temp/";
            this.ButtonText = "Upload file(s)";
            this.UploadCompleteCallback = string.Empty;

            //this.CustomSettings = new CUploadCustomSettings(this);
            _ctrlFileUploadCollection = new HtmlInputHidden();
            _ctrlFileUploadCollection.ID = "FileUploadCollection";
            _ctrlFileUploadCollection.Value = string.Empty;

            _ctrlSelectedIndex = new HtmlInputHidden();
            _ctrlSelectedIndex.ID = "SelectedIndex";
            _ctrlSelectedIndex.Value = string.Empty;

            this.Init += new EventHandler(FlashUpload_Init);
        }

        void FlashUpload_Init(object sender, EventArgs e)
        {
            HtmlLink flashCss = new HtmlLink();
            flashCss.Href = "~/FlashUpload/Css/Default.css";
            flashCss.Attributes["type"] = "text/css";
            flashCss.Attributes["rel"] = "Stylesheet";

            Page.Header.Controls.Add(flashCss);
        }
        #endregion

        #region Override Methods
        public override string ClientID
        {
            get
            {
                return base.ClientID;
            }
        }
        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }
        protected override void OnInit(EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "FileUploadControlFile_swfupload", Page.ResolveUrl(CoreScriptPath) + "swfupload.js");
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "FileUploadControlFile_swfupload.swfobject", Page.ResolveUrl(CoreScriptPath) + "swfupload.swfobject.js");
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "FileUploadControlFile_swfupload.queue", Page.ResolveUrl(CoreScriptPath) + "swfupload.queue.js");
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "FileUploadControlFile_fileprogress", Page.ResolveUrl(CoreScriptPath) + "fileprogress.js");
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "FileUploadControlFile_handlers", Page.ResolveUrl(CoreScriptPath) + "handlers.js");
            Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "FileUploadCollection", Page.ResolveUrl(CoreScriptPath) + "FileUploadedCollection.js");

            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "FileUploadStart", "", true);

            base.OnInit(e);
        }
        protected override void CreateChildControls()
        {
            Controls.Clear();

            if (this.CustomSettings == null)
                this.CustomSettings = new FlashUploadSetting();

            //_ctrlFileUploadedNameCollection.Value = _fileUploadedNameCollection;

            this.Controls.Add(_ctrlFileUploadCollection);
            this.Controls.Add(_ctrlSelectedIndex);

            //_templateOwner = new CTemplateOwner(_ctrlFileUploadedNameCollection.ClientID, _ctrlDefaultFileUploaded.ClientID, CoreScriptPath, CoreFlashFile, CoreHandlerFile, PreviewHandlerFile, SaveToPath, Text, CustomSettings);            

            ITemplate layoutTemplate = _layoutTemplate;
            ITemplate errorTemplate = _errorTemplate;
            if (layoutTemplate == null)
            {
                layoutTemplate = new FlashUploadLayoutTemplate();
            }
            if (errorTemplate == null)
            {
                errorTemplate = new FlashUploadErrorTemplate();
            }

            layoutTemplate.InstantiateIn(this);
            errorTemplate.InstantiateIn(this);

            //this.Controls.Add(_templateOwner);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);
            StringBuilder sb = new StringBuilder();

            sb.Append("<script type='text/javascript'> \n")
            .Append("var _").Append(this._ctrlFileUploadCollection.ClientID).Append(" = new FileUploadCollection();")
            .Append("var ").Append(this.ClientID).Append("; \n ")
            .Append("$(document).ready(function () { \n ")
            .Append("    var settings = { \n ")
            .Append("        flash_url : '").Append(HttpContext.Current.Server.UrlPathEncode(Page.ResolveUrl(this.CoreFlashFile))).Append("', \n ")
            .Append("        upload_url: '").Append(HttpContext.Current.Server.UrlPathEncode(Page.ResolveUrl(this.CoreHandlerFile))).Append("?Overwrite=").Append(this.CustomSettings.EnableFileOverwrite.ToString().ToLower()).Append("&Path=").Append(HttpContext.Current.Server.UrlPathEncode(Page.ResolveUrl(this.SaveToPath))).Append("', \n ")
            .Append("        file_size_limit : '").Append((float)this.CustomSettings.FileSizeLimit / 1024).Append(" MB', \n ")
            .Append("        file_types : '").Append(GetFileTypes(this.CustomSettings.AllowedFileExtentions)).Append("', \n ")
            .Append("        file_types_description : '").Append(this.CustomSettings.FileDescription).Append("', \n ")
            .Append("        file_upload_limit : 0, ")//.Append(this.CustomSettings.FileUploadLimit).Append(", \n ")
            .Append("        file_queue_limit : 0, \n ")
            .Append("        custom_settings : { \n ")
            .Append("            previewHandlerFile: '").Append(Page.ResolveUrl(this.PreviewHandlerFile)).Append("',")
            .Append("            progressTarget : '").Append(this.CustomSettings.TargetSettings.ProgressTarget).Append("',")
            .Append("            loadingContentTarget : '").Append(this.CustomSettings.TargetSettings.LoadingContentTarget).Append("',")
            .Append("            longLoadingTarget : '").Append(this.CustomSettings.TargetSettings.LongLoadingTarget).Append("',")
            .Append("            alternateContentTarget : '").Append(this.CustomSettings.TargetSettings.AlternateContentTarget).Append("',")
            .Append("            cancelButtonTarget : '").Append(this.CustomSettings.ButtonSettings.CancelButtonTarget).Append("',")
            .Append("            statusTarget : '").Append(this.CustomSettings.TargetSettings.StatusTarget).Append("',")
            .Append("            fileUploadLimit: ").Append(this.CustomSettings.FileUploadLimit).Append(",")
            .Append("            progressID: '',");
            //.Append(this.FileProgressID).Append("_',")
            if (!string.IsNullOrEmpty(this.UploadCompleteCallback))
            {
                sb.Append("            uploadCompleteCallback: ").Append(this.UploadCompleteCallback).Append(",");
            }
            sb.Append("            fileUploadCollectionID: '").Append(this._ctrlFileUploadCollection.ClientID).Append("',")
            .Append("            selectedIndexID: '").Append(this._ctrlSelectedIndex.ClientID).Append("',")
            .Append("            fileUploadCollectionObject: _").Append(this._ctrlFileUploadCollection.ClientID).Append("")
            .Append("        }, \n ")
            .Append("        debug: ").Append(this.CustomSettings.EnableDebugging.ToString().ToLower()).Append(", \n ")
            .Append("        // Button Settings \n ")
            .Append("        button_placeholder_id : '").Append(this.CustomSettings.ButtonSettings.ButtonHolder).Append("', \n ")
            .Append("        button_width: ").Append(this.CustomSettings.ButtonSettings.Width).Append(", \n ")
            .Append("        button_height: ").Append(this.CustomSettings.ButtonSettings.Height).Append(", \n ");
            if (!string.IsNullOrEmpty(this.CustomSettings.ButtonSettings.Text))
            {
                sb.Append("        button_text: '").Append(this.CustomSettings.ButtonSettings.Text).Append("', \n ");
            }
            if(!string.IsNullOrEmpty(this.CustomSettings.ButtonSettings.ImageUrl))
            {
                sb.Append("        button_image_url: '").Append(Page.ResolveUrl(this.CustomSettings.ButtonSettings.ImageUrl)).Append("', \n ");
            }
            if (!string.IsNullOrEmpty(this.CustomSettings.ButtonSettings.StyleText))
            {
                sb.Append("        button_style: '").Append(this.CustomSettings.ButtonSettings.StyleText).Append("', \n ");
            }
            if (this.CustomSettings.ButtonSettings.TextLeftPadding > 0)
            {
                sb.Append("        button_text_left_padding: '").Append(this.CustomSettings.ButtonSettings.TextLeftPadding).Append("', \n ");
            }
            if (this.CustomSettings.ButtonSettings.TextTopPadding > 0)
            {
                sb.Append("        button_text_top_padding: '").Append(this.CustomSettings.ButtonSettings.TextTopPadding).Append("', \n ");
            }
            sb.Append("        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT, \n ")
            .Append("        button_cursor: SWFUpload.CURSOR.HAND, \n ")
            .Append("        // The event handler functions are defined in handlers.js \n ")
            .Append("        swfupload_loaded_handler : swfUploadLoaded, \n ")
            .Append("        file_queued_handler : fileQueued, \n ")
            .Append("        file_queue_error_handler : fileQueueError, \n ")
            .Append("        file_dialog_complete_handler : fileDialogComplete, \n ")
            .Append("        upload_start_handler : uploadStart, \n ")
            .Append("        upload_progress_handler : uploadProgress, \n ")
            .Append("        upload_error_handler : uploadError, \n ")
            .Append("        upload_success_handler : uploadSuccess, \n ")
            .Append("        upload_complete_handler : uploadComplete, \n ")
            .Append("        queue_complete_handler : queueComplete,	// Queue plugin event \n ")
            .Append("        // SWFObject settings \n ")
            .Append("        minimum_flash_version : '9.0.28', \n ")
            .Append("        swfupload_pre_load_handler : swfUploadPreLoad, \n ")
            .Append("        swfupload_load_failed_handler : swfUploadLoadFailed \n ")
            .Append("    }; \n ")
            .Append("    ").Append(this.ClientID).Append(" = new SWFUpload(settings); \n ")
            .Append("\n  loadArray(").Append(this.ClientID).Append(");")
            .Append("}); \n ")
            .Append("</script> \n ");
            writer.Write(sb);
        }
        #endregion

        private string GetFileTypes(string allowedFileExtentions)
        {
            if (allowedFileExtentions == "*.*") return allowedFileExtentions;
            string[] s = allowedFileExtentions.Replace(" ", "").Split(',');

            string outStr = "";

            for (int i = 0; i < s.Length; i++)
                if (outStr.Length == 0) outStr += "*." + s[i];
                else outStr += ";*." + s[i];

            return outStr;
        }
    }

    public class FlashUploadLayoutTemplate : ITemplate
    {

        #region ITemplate Members

        void ITemplate.InstantiateIn(Control container)
        {
            FlashUpload owner = (FlashUpload)container;
            StringBuilder sb = new StringBuilder();

            //<div id="divSWFUploadUI">
            //    <div class="fieldset flash" id="fsUploadProgress">
            //    <span class="legend"><span id="spanButtonPlaceholder"></span><span id="btnUpload" type="button">Upload files</span>

            //    </div>
            //    <p id="divStatus">0 Files Uploaded</p>
            //    <p>
            //        
            //        <input id="btnCancel" type="button" value="Cancel All Uploads" disabled="disabled" style="margin-left: 2px; height: 22px; font-size: 8pt;" />
            //    </p>
            //    <br style="clear: both;" />

            //</div>
            sb.Append("<div id=\"").Append(owner.CustomSettings.TargetSettings.ProgressTarget).Append("\" class=\"fieldset flash\"> \n");
            sb.Append("<div class=\"legend\"> \n");
            sb.Append("<span id=\"").Append(owner.CustomSettings.ButtonSettings.ButtonHolder).Append("\"></span>");
            //sb.Append("<span id=\"").Append(owner.CustomSettings.UploadButtonID).Append("\">").Append(owner.ButtonText).Append("</span>");
            sb.Append("<span>").Append(owner.ButtonText).Append("</span>");
            sb.Append("</div> \n");
            sb.Append("</div> \n");
            sb.Append("<p style=\"margin-left: 7px;\" id=\"").Append(owner.CustomSettings.TargetSettings.StatusTarget).Append("\"></p> \n");
            sb.Append("<p style=\"margin-left: 7px;\">")
                .Append("<input id=\"").Append(owner.CustomSettings.ButtonSettings.ButtonID).Append("\" type=\"button\" value=\"").Append(owner.CustomSettings.ButtonSettings.Text).Append("\" onclick=\"").Append(owner.ClientID).Append(".startUpload()\" >")
                .Append("<input id=\"").Append(owner.CustomSettings.ButtonSettings.CancelButtonTarget).Append("\" type=\"button\" value=\"Cancel all uploads\"");
            if (owner.CustomSettings.ButtonSettings.EnableCancelButton) sb.Append(" disabled=\"disabled\" ");
            sb.Append(" style=\"margin-left: 2px; height: 22px; font-size: 8pt; display: none;\" /></p> \n");
            sb.Append("<br style=\"clear: both;\" /> \n");

            HtmlGenericControl div = new HtmlGenericControl("div");
            div.ID = "divSWFUploadUI";
            div.InnerHtml = sb.ToString();

            owner.Controls.Add(div);
        }

        #endregion
    }
    public class FlashUploadErrorTemplate : ITemplate
    {
        #region ITemplate Members

        void ITemplate.InstantiateIn(Control container)
        {
            FlashUpload owner = (FlashUpload)container;

            StringBuilder sb = new StringBuilder();
            //<noscript style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px;">
            //    We're sorry.  SWFUpload could not load.  You must have JavaScript enabled to enjoy SWFUpload.
            //</noscript>
            //<div id="divLoadingContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
            //    SWFUpload is loading. Please wait a moment...
            //</div>
            //<div id="divLongLoading" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
            //    SWFUpload is taking a long time to load or the load has failed.  Please make sure that the Flash Plugin is enabled and that a working version of the Adobe Flash Player is installed.
            //</div>
            //<div id="divAlternateContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">

            //    We're sorry.  SWFUpload could not load.  You may need to install or upgrade Flash Player.
            //    Visit the <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">Adobe website</a> to get the Flash Player.
            //</div>
            sb.Append("<noscript style=\"background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966;\">")
                .Append("We're sorry.  SWFUpload could not load.  You must have JavaScript enabled to enjoy SWFUpload.").Append("</noscript>")
                .Append("<div id=\"").Append(owner.CustomSettings.TargetSettings.LoadingContentTarget).Append("\" class=\"content\" style=\"background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;\">").Append("SWFUpload is loading. Please wait a moment...").Append("</div> \n")
                .Append("<div id=\"").Append(owner.CustomSettings.TargetSettings.LongLoadingTarget).Append("\" class=\"content\" style=\"background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;\">").Append("SWFUpload is taking a long time to load or the load has failed.  Please make sure that the Flash Plugin is enabled and that a working version of the Adobe Flash Player is installed.").Append("</div> \n")
                .Append("<div id=\"").Append(owner.CustomSettings.TargetSettings.AlternateContentTarget).Append("\" class=\"content\" style=\"background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;\">").Append("We're sorry.  SWFUpload could not load.  You may need to install or upgrade Flash Player. \n Visit the <a href=\"http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash\">Adobe website</a> to get the Flash Player.").Append("</div> \n");

            HtmlGenericControl div = new HtmlGenericControl("div");
            div.InnerHtml = sb.ToString();

            owner.Controls.Add(div);
        }

        #endregion
    }

    public class FlashUploadSetting
    {
        #region Public Properties
        public int FileSizeLimit { get; set; }
        public int FileUploadLimit { get; set; }
        public bool EnableDebugging { get; set; }
        public bool EnableFileOverwrite { get; set; }
        public string FileDescription { get; set; }
        public string AllowedFileExtentions { get; set; }
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [NotifyParentProperty(true)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public FlashUploadTargetSetting TargetSettings { get; private set; }
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [NotifyParentProperty(true)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public FlashUploadButtonSetting ButtonSettings { get; private set; }
        #endregion

        #region Constructor
        public FlashUploadSetting()
        {
            this.FileSizeLimit = 2048;
            this.FileUploadLimit = 6;
            this.EnableDebugging = false;
            this.EnableFileOverwrite = false;
            this.FileDescription = "All files";
            this.AllowedFileExtentions = "*.*";

            this.TargetSettings = new FlashUploadTargetSetting();
            this.ButtonSettings = new FlashUploadButtonSetting();
        }
        public FlashUploadSetting(Control owner)
        {
            this.FileSizeLimit = 2048;
            this.FileUploadLimit = 6;
            this.EnableDebugging = false;
            this.EnableFileOverwrite = false;
            this.FileDescription = "All files";
            this.AllowedFileExtentions = "*.*";

            this.TargetSettings = new FlashUploadTargetSetting(owner);
            this.ButtonSettings = new FlashUploadButtonSetting(owner);
        }
        #endregion
    }
    public class FlashUploadTargetSetting
    {
        public string ProgressTarget { get; set; }
        public string LoadingContentTarget { get; set; }
        public string LongLoadingTarget { get; set; }
        public string AlternateContentTarget { get; set; }

        public string StatusTarget { get; set; }

        public FlashUploadTargetSetting()
        {
            this.ProgressTarget = "_fsUploadProgress";
            this.LoadingContentTarget = "_divLoadingContent";
            this.LongLoadingTarget = "_divLongLoading";
            this.AlternateContentTarget = "_divAlternateContent";
            this.StatusTarget = "_divStatus";
        }
        public FlashUploadTargetSetting(Control owner)
        {
            this.ProgressTarget = owner.ClientID + "_fsUploadProgress";
            this.LoadingContentTarget = owner.ClientID + "_divLoadingContent";
            this.LongLoadingTarget = owner.ClientID + "_divLongLoading";
            this.AlternateContentTarget = owner.ClientID + "_divAlternateContent";
            this.StatusTarget = owner.ClientID + "_divStatus";
        }
    }
    public class FlashUploadButtonSetting
    {
        public int Width { get; set; }
        public int Height { get; set; }
        public string ButtonID { get; set; }
        public string Text { get; set; }
        public string StyleText { get; set; }
        public string ButtonHolder { get; set; }
        public bool EnableCancelButton { get; set; }
        public string CancelButtonTarget { get; set; }
        public string ImageUrl { get; set; }
        public int TextTopPadding { get; set; }
        public int TextLeftPadding { get; set; }

        public FlashUploadButtonSetting()
        {
            this.ButtonID = "_btnUpload";
            this.Height = 22;
            this.Width = 110;
            this.Text = "upload";
            this.ButtonHolder = "_spanButtonPlaceHolder";
            this.EnableCancelButton = false;
            this.CancelButtonTarget = "_btnCancel";
            this.StyleText = string.Empty;
            this.ImageUrl = string.Empty;
            this.TextLeftPadding = 0;
            this.TextTopPadding = 0;
        }

        public FlashUploadButtonSetting(Control owner)
            : this()
        {
            this.ButtonID = owner.ClientID + "_btnUpload";
            this.Height = 22;
            this.Width = 110;
            this.Text = "upload";
            this.ButtonHolder = owner.ClientID + "_spanButtonPlaceHolder";
            this.EnableCancelButton = false;
            this.CancelButtonTarget = owner.ClientID + "_btnCancel";
            this.StyleText = string.Empty;
            this.ImageUrl = string.Empty;
            this.TextLeftPadding = 0;
            this.TextTopPadding = 0;
        }
    }

    public class FlashUploadDesigner : ControlDesigner
    {
        public override void Initialize(IComponent component)
        {
            base.Initialize(component);
            SetViewFlags(ViewFlags.TemplateEditing, true);
        }

        public override string GetDesignTimeHtml()
        {
            return "<span>SWFUpload Control</span>";
            //return base.GetDesignTimeHtml();
        }

        public override TemplateGroupCollection TemplateGroups
        {
            get
            {
                TemplateGroupCollection collection = new TemplateGroupCollection();
                TemplateGroup layoutGroup;
                TemplateGroup errorGroup;
                TemplateDefinition template;
                FlashUpload control;

                control = (FlashUpload)Component;
                layoutGroup = new TemplateGroup("Layout");
                errorGroup = new TemplateGroup("Error");

                template = new TemplateDefinition(this, "Template", control, "Template", true);
                collection.Add(layoutGroup);
                collection.Add(errorGroup);
                return collection;
            }
        }
    }
}